#!/bin/bash

# 检查参数是否存在
if [ $# -ne 2 ]; then
    echo "Usage: $0 <ubuntu_version> <image_type>"
    echo "Available versions   : 20, 22, 24"
    echo "Available image types: base, linux"
    exit 1
fi

# 获取参数
UBUNTU_VERSION=$1
IMAGE_TYPE=$2

# 定义合法的 Ubuntu 版本数组
VALID_VERSIONS=("20" "22" "24")

# 检查参数是否在合法版本中
if [[ ! " ${VALID_VERSIONS[@]} " =~ " ${UBUNTU_VERSION} " ]]; then
    echo "Error: Invalid Ubuntu version specified"
    echo "Available versions: ${VALID_VERSIONS[*]}"
    exit 1
fi

# 校验镜像类型
VALID_IMAGE_TYPES=("base" "linux" "yoc" "jsapp" "aosp")
if [[ ! " ${VALID_IMAGE_TYPES[@]} " =~ " ${IMAGE_TYPE} " ]]; then
    echo "Error: Invalid image type specified"
    echo "Available types: ${VALID_IMAGE_TYPES[*]}"
    exit 1
fi

# 动态生成 Dockerfile 路径和镜像标签
DOCKERFILE="./Dockerfile.${IMAGE_TYPE}"
IMAGE_TAG="linux-dev-${IMAGE_TYPE}:${UBUNTU_VERSION}.04"
# echo "[debug]: DOCKERFILE: ${DOCKERFILE}" 
# echo "[debug]: IMAGE_TAG: ${IMAGE_TAG}" 

# 检查 Dockerfile 是否存在
if [ ! -f "$DOCKERFILE" ]; then
    echo "Error: Dockerfile not found at $DOCKERFILE"
    exit 1
fi

cd attachments
cp -a tsinghua.sources.${UBUNTU_VERSION}.04.list tsinghua.sources.list.tmp
cp -a ustc.sources.${UBUNTU_VERSION}.04.list ustc.sources.list.tmp
cd -

export DOCKER_BUILDKIT=1  # 启用 BuildKit

# 执行构建命令
echo "Building image with Ubuntu $UBUNTU_VERSION and type $IMAGE_TYPE..."
# echo "[debug]: docker build --progress=plain --build-arg UBUNTU_VERSION=\"${UBUNTU_VERSION}\" -t \"${IMAGE_TAG}\" -f \"${DOCKERFILE}\" ." 
docker build --progress=plain --build-arg UBUNTU_VERSION="$UBUNTU_VERSION" --build-arg UID=`id -u` -t "$IMAGE_TAG" -f "$DOCKERFILE" .
# docker build --debug --build-arg UBUNTU_VERSION="$UBUNTU_VERSION" -t "$IMAGE_TAG" -f "$DOCKERFILE" .

rm attachments/tsinghua.sources.list.tmp
rm attachments/ustc.sources.list.tmp
